package com.yyhh.helpcall.http.interceptor;

import com.yyhh.helpcall.MainApplication;
import com.yyhh.helpcall.utils.AppUtils;
import com.yyhh.helpcall.utils.NetLog;
import com.yyhh.helpcall.utils.SpUtils;
import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PublicParamsInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        String deviceId = AppUtils.getDeviceId(MainApplication.mainApplication);
        String token = SpUtils.getInstance(MainApplication.mainApplication).getString("token");
        String appVersion = AppUtils.getVersionName(MainApplication.mainApplication);
        NetLog.d("deviceId = " + deviceId);
        NetLog.d("token = " + token);

        String method = chain.request().method();
        Response response = null;
        if(method == "GET"){
            HttpUrl url = chain.request().url();
            HttpUrl newUrl = url.newBuilder()
                    .addQueryParameter("app_version", appVersion)
                    .addQueryParameter("imei", deviceId)
                    .addQueryParameter("token",token )
                    .build();
            response = chain.proceed(chain.request().newBuilder().url(newUrl).build());
        }else if(method == "POST"){
            RequestBody body = chain.request().body();
            if(body != null && body instanceof FormBody){
                FormBody formBody = (FormBody) body;
                FormBody.Builder builder = new FormBody.Builder();
                builder.add("app_version",appVersion)
                        .add("imei",deviceId)
                        .add("token",token);
                for(int i = 0; i < formBody.size(); i ++){
                    builder.add(formBody.name(i),formBody.value(i));
                }
                response = chain.proceed(chain.request().newBuilder().post(builder.build()).build());
            }else{
                response = chain.proceed(chain.request());
            }
        }else{
            response = chain.proceed(chain.request());
        }
        return response;
    }
}
